<template>
    <div class="message" v-scroll-bottom="session.messages">
        <ul v-if="session">
            <li class="message-li" v-for="item in session.messages">
                <p class="time">
                    <span>{{ time(item.date) }}</span>
                </p>
                <div class="main" :class="{ self: item.self }">
                    <img class="avatar" width="30" height="30" :src="item.self ? user.img : session.user.img"/>
                    <div class="text">{{ item.content }}</div>
                </div>
            </li>
        </ul>
    </div>
</template>

<script>
import {useStore} from "vuex";
import {computed,nextTick} from "vue";
export default {
    setup() {
        let store = useStore()
        let sessionList=computed(() => store.state.sessions);
        let currentSessionId=computed(() => store.state.currentSessionId);
        let findSession=()=>{
            return sessionList.value.find(session => session.id === currentSessionId.value);
        }
        let session=findSession();
        // console.log('ccccchj',sessionList.value[0].messages[1].date);
        let time = (date)=>{
            if (typeof date === 'string') {
                date = new Date(date);
            }
            return date.getHours() + ':' + date.getMinutes();
        }
        return {
            session,
            user: computed(() => store.state.user),
            time,
        };
    },
    directives: {
        // 发送消息后滚动到底部
        'scroll-bottom' :function (vm,el) {
            nextTick(() => {
                el.scrollTop = el.scrollHeight - el.clientHeight;
            });
        }
    },
    
    
}
</script>

<style scoped>
.message {
    padding: 10px 15px;
    overflow-y: scroll;
}

.message-li {
    margin-bottom: 15px;
}

.time {
    margin: 7px 0;
    text-align: center;
}

.time span {
    display: inline-block;
    padding: 0 18px;
    font-size: 12px;
    color: #fff;
    border-radius: 2px;
    background-color: #dcdcdc;
}

.avatar {
    float: left;
    margin: 0 10px 0 0;
    border-radius: 3px;
}

.text {
    display: inline-block;
    
    position: relative;
    padding: 0 10px;
    /*max-width: ~ 'calc(100% - 40px)';*/
    min-height: 30px;
    line-height: 2.5;
    font-size: 12px;
    text-align: left;
    word-break: break-all;
    background-color: #fafafa;
    border-radius: 4px;
}

.text :before {
    content: " ";
    position: absolute;
    top: 9px;
    right: 100%;
    border: 6px solid transparent;
    border-right-color: #fafafa;
}

.self {
    text-align: right;
}

.self .avatar {
    float: right;
    margin: 0 0 0 10px;
}

.self .text {
    background-color: #b2e281;
}

.self .text :before {
    right: inherit;
    left: 100%;
    border-right-color: transparent;
    border-left-color: #b2e281;
}


</style>